package com.ke.rule.base;


import org.apache.commons.lang3.StringUtils;
import java.util.*;

/**
 * 异常工具类
 * 
 * @author guyu
 */
public final class BusinessExceptionUtils {

  /**
   * 对问题列表按group和type进行分组
   * 
   * 结构为：
   * 
   * <pre>
   *    {
   *        <group>: {
   *            <ProblemTypeEnum>: [problem list],
   *        }
   *    }
   * </pre>
   * 
   * 其中对于没有group的，归到default groups
   * 
   * @param problems
   * @return
   */
  public static Map<String, Map<ProblemTypeEnum, List<Problem>>> groupByType(List<Problem> problems) {
    Map<String, Map<ProblemTypeEnum, List<Problem>>> groups = new LinkedHashMap<>();
    
    problems.forEach(p -> {
      Problem pc = p.clone();

      String group = pc.getGroup();
      if (StringUtils.isBlank(group)) {
        group = "default";
      }
      pc.setGroup(null);

      if (StringUtils.isNotBlank(pc.getCode())) {
        String msg = pc.getMessage();
        if (StringUtils.isBlank(msg)) {
          msg = pc.getDescription();
        }
        BusinessException be = new BusinessException(pc.getCode(), msg);
        be.setArgs(pc.getArgs());
        pc.setMessage(be.getMessage());
      }

      Map<ProblemTypeEnum, List<Problem>> groupByType = groups.get(group);
      if (groupByType == null) {
        groupByType = new LinkedHashMap<>();
        groups.put(group, groupByType);
      }
      List<Problem> groupingProblems = groupByType.get(pc.getType());
      if (null == groupingProblems) {
        groupingProblems = new ArrayList<Problem>();
        groupByType.put(pc.getType(), groupingProblems);
      }
      groupingProblems.add(pc);
    });
    
    return groups;
  }
  
}
